import csv
from django.http import HttpResponse
from django.core.paginator import Paginator
from rest_framework.decorators import api_view, permission_classes, authentication_classes
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from .serializers import RegisterSerializer

# 1. 注册   POST /api/register
@api_view(['POST'])
@permission_classes([AllowAny])
def register(request):
    ser = RegisterSerializer(data=request.data)
    ser.is_valid(raise_exception=True)
    user = ser.save()
    return Response({
        'status':200,
        'data': {
            'msg': '注册成功', 
            'id': user.id}
            }, 
        status=status.HTTP_201_CREATED)

# 2. 登录   POST /api/login
@api_view(['POST'])
@permission_classes([AllowAny])
def login(request):
    username = request.data.get('username')
    password = request.data.get('password')
    # 验证用户名和密码
    user = authenticate(username=username, password=password)
    if user is None:
        return Response({
            'status': 400,
            'data': {
                'msg': '用户名或密码错误'
            }
        }, status=status.HTTP_400_BAD_REQUEST)
    refresh = RefreshToken.for_user(user)
    return Response({
        'status': 200,
        'data': {
            'msg': '登录成功',
            'access': str(refresh.access_token),
            'refresh': str(refresh),
        }
    }, status=status.HTTP_200_OK)

# 3. 用户信息  GET /my/userinfo  （需 token）
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def user_info(request):
    user = request.user
    return Response({
        'status': 200,
        'data': {
            'msg': '获取用户信息成功',
            'info': {
                'id': user.id,
                'username': user.username,
            }
        }
    }, status=status.HTTP_200_OK)

# 4. 退出登录  POST /my/logout
@api_view(['POST'])
@authentication_classes([])  # 明确禁用所有认证
@permission_classes([AllowAny])  # 明确允许所有访问
def logout(request):
    try:
        # 简单的退出登录，前端清除token即可
        # 不需要认证，因为退出登录主要是前端行为
        return Response({
            'status': 200,
            'data': {
                'msg': '退出登录成功'
            }
        }, status=status.HTTP_200_OK)
    except Exception as e:
        return Response({
            'status': 400,
            'data': {
                'msg': '退出登录失败'
            }
        }, status=status.HTTP_400_BAD_REQUEST)

# 测试方法 （练习分页）
@api_view(['GET'])
@permission_classes([AllowAny])
def test_page(request):
    page_num = request.GET.get('page_num', 1)
    all_data=[1,2,3,4,5,6,7,8,9,10]
    # 一页两个
    paginator = Paginator(all_data, 2)
    # 初始化具体页码的page对象  （page对象就是掌管那一页的对象）
    page_obj = paginator.get_page(int(page_num))
    # 分页数据
    page_data = page_obj.object_list
    return Response({
        'status': 200,
        'total': paginator.count,
        'data': {
            'msg': '获取成功',
            'page_data': page_data,
            'total_page': paginator.num_pages,
            'current_page': page_obj.number,
        }
    }, status=status.HTTP_200_OK)

# 练习csv下载
@api_view(['GET'])
@permission_classes([AllowAny])
def test_csv(request):
    response = HttpResponse(content_type='text/csv; charset=utf-8')
    response['Content-Disposition'] = 'attachment; filename="users.csv"'
    # 添加BOM头，确保Excel能正确识别UTF-8编码
    response.write('\ufeff')
    writer = csv.writer(response)
    writer.writerow(['用户ID', '用户名'])
    
    # 获取所有Django用户并写入CSV
    users = User.objects.all()
    for user in users:
        writer.writerow([user.id, user.username])
    
    return response

    

 